import { FC, PropsWithChildren, useState, useRef, useEffect } from "react";
import { throttle } from "@/util/index";
type Props = {
  dataList: MessageType[];
  itemHeight: number;
  renderItem: (item: MessageType) => JSX.Element;
};
import { type MessageType } from "@/api/xhr/message/index";
const VirtualScoll: FC<PropsWithChildren<Props>> = props => {
  const { renderItem, dataList, itemHeight } = props;
  const emptyHeight = dataList.length * itemHeight;
  const [renderList, setRenderList] = useState<MessageType[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const renderItems = () => {
    if (typeof renderItem !== "function") {
      console.error("renderItem must be a function");
      return null;
    }
    return renderList.map(item => renderItem(item));
  };

  const [scrollInfo, setScrollInfo] = useState({
    start: 0,
    end: 0
  });
  const [renderNumber, setRenderNumber] = useState(0);
  const [offset, setOffset] = useState(0);

  useEffect(() => {
    if (containerRef.current && contentRef.current) {
      setRenderNumber(
        Math.ceil(containerRef.current?.clientHeight / itemHeight)
      );
      setScrollInfo({
        start: 0,
        end: Math.ceil(containerRef.current?.clientHeight / itemHeight)
      });
    }
  }, []);
  
  useEffect(() => {
    setRenderList(
      dataList.slice(
        scrollInfo.start,
        Math.min(scrollInfo.end, dataList.length)
      )
    );
  }, [dataList, scrollInfo.start, scrollInfo.end]);
  
  const handleScroll = throttle((e: React.UIEvent<HTMLDivElement>) => {
    // 滚动事件
    const scrollTop = (e.target as HTMLDivElement).scrollTop;
    const newStart = Math.floor(scrollTop / itemHeight);
    const newEnd = newStart + renderNumber;
    
    // 只有当开始或结束索引发生变化时才更新状态
    if (newStart !== scrollInfo.start || newEnd !== scrollInfo.end) {
      setScrollInfo({
        start: newStart,
        end: newEnd
      });
      setOffset(newStart * itemHeight);
    }
  });
  const style = "absolute top-0 left-0 w-full";
  return (
    <div
      className="relative overflow-y-scroll h-full w-full scrollbar-hide"
      ref={containerRef}
      onScroll={handleScroll}
    >
      <div className={"w-full"} style={{ height: emptyHeight + "px" }}></div>
      <div
        ref={contentRef}
        className={style}
        style={{ transform: `translateY(${offset}px)` }}
      >
        {renderItems()}
      </div>
    </div>
  );
};

export default VirtualScoll;
